package run.vueblog.app.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import run.vueblog.app.entity.User;
import run.vueblog.app.service.UserService;
import run.vueblog.app.util.JwtUtils;

/**
 * @Author: zhanghuan
 * @date: 2020/8/3 20:24
 * @description:
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken) token;

        // 根据token获取user的id
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();

        // 根据id查出user
        User user = userService.getById(Long.valueOf(userId));
        //用户不存在
        if (user == null) {
            throw new UnknownAccountException("账户不存在!");

        }
        //如果用户被锁
        if (user.getStatus() == -1) {
            throw new LockedAccountException("账户已被锁定!");

        }
        AccountProfile profile = new AccountProfile();
        BeanUtils.copyProperties(user, profile);
        // 把用户的基本信息，返回给shiro
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(),getName());
    }
}
